package com.uniview.web.contorller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.uniview.base.BaseController;
import com.uniview.common.mapper.JsonMapper;
import com.uniview.entity.po.Employees;
import com.uniview.entity.po.Menu;
import com.uniview.entity.po.ResourceRole;
import com.uniview.entity.po.Role;
import com.uniview.entity.po.UserRole;
import com.uniview.entity.vo.MenuRole;
import com.uniview.entity.vo.Pager;
import com.uniview.entity.vo.Query;
import com.uniview.entity.vo.QueryBuilder;
import com.uniview.entity.vo.ResultMessage;
import com.uniview.enums.EAndOR;
import com.uniview.enums.EMatchMode;
import com.uniview.enums.EOrderMode;
import com.uniview.service.EmployeesService;
import com.uniview.service.MenuService;
import com.uniview.service.RoleService;
import com.uniview.util.DateUtil;

@Controller
@RequestMapping(value="/sys")
public class RoleController extends BaseController {
	
	Logger logger = Logger.getLogger(RoleController.class);
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private MenuService menuService;

	@Autowired
	private EmployeesService employeesService;
	
	@RequestMapping(value="/role")
	public ModelAndView roleHomeView(HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new ModelAndView("sys/role");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("roles", findAllRole());
		view.addObject("basePath", basePath);
		return view;
	}
	
	@RequestMapping(value="/roleSource")
	public ModelAndView roleSourceView(HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new ModelAndView("views/sys/roleSource");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}
	
	@RequestMapping(value="/roleUserManagement")
	public ModelAndView roleUserManagementView(HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new ModelAndView("views/sys/roleUserManagement");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}
	
	@RequestMapping(value="/roleUserRight")
	public ModelAndView roleRightView(HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new ModelAndView("views/sys/roleUserRight");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}
	
	@RequestMapping(value="/roleUserLeft")
	public ModelAndView roleLeftView(HttpServletRequest request, HttpServletResponse response){
		ModelAndView view = new ModelAndView("views/sys/roleUserLeft");
		String basePath = request.getServletContext().getContextPath();
		view.addObject("basePath", basePath);
		return view;
	}
	
	/**
	 * 查找所有的角色
	 * @return
	 */
	@RequestMapping(value="/findAllRole")
	@ResponseBody
	public List<Role> findAllRole(){
		return roleService.findAllRole();
	}
	
	@RequestMapping(value="/findRoleByPage")
	@ResponseBody
	public String findRoleByPage(HttpServletRequest request,Integer page,Integer limit,String roleName){
		QueryBuilder queryBuilder = new QueryBuilder(Role.class.getName());
		Query query = new Query("roleName", EMatchMode.LIKE, roleName);
		queryBuilder.add(query);
		queryBuilder.setOrderCols("id");
		queryBuilder.setOrderMode(EOrderMode.DESC);
		Pager<Role> pager = roleService.findRoleByPager(queryBuilder, limit, page);
		List<Role> roleList = pager.getPagerList();
		Integer count = pager.getTotalRow();
		return getTableJsonString(JsonMapper.toJsonString(roleList),count);
	}
	
	@RequestMapping(value="/addRole")
	@ResponseBody
	public ResultMessage addRole(Role role){
		String message = "";
		boolean success = false;
		try{
			role.setCreated(new Date());
			role.setModified(new Date());
			int roleId = roleService.saveRole(role);
			if(roleId >0){
				success = true;
				message = "角色添加成功!";
			}else{
				message = "角色添加失败!";
			}
		}catch(Exception e){
			message = "数据操作异常!";
			logger.error(message, e);
		}
		
		return getResult(message, success);
	}
	
	@RequestMapping(value="/updateRole")
	@ResponseBody
	public ResultMessage updateRole(Role role){
		String message = "";
		boolean success = false;
		try{
			role.setModified(new Date());
			boolean result = roleService.updateRole(role);
			if(result){
				success = true;
				message = "角色信息修改成功!";
			}else{
				message = "角色信息修改失败!";
			}
		}catch(Exception e){
			message = "数据操作异常!";
			logger.error(message, e);
		}
		return getResult(message, success);
	}
	
	@RequestMapping(value="/loadRoleById")
	@ResponseBody
	public Role loadRoleById(int roleId){
		try{
			return roleService.findRoleById(roleId);
		}catch(Exception e){
			logger.error("获取角色信息异常", e);
		}
		return null;
	}
	
	
	@RequestMapping(value="/deleteRoleById")
	@ResponseBody
	public ResultMessage deleteRoleById(int roleId){
		String message = "";
		boolean success = false;
		try{
			boolean result = roleService.deleteRole(roleId);
			if(result){
				success = true;
				message = "角色信息删除成功!";
			}else{
				message = "角色信息删除失败!";
			}
		}catch(Exception e){
			message = "数据操作异常!";
			logger.error(message, e);
		}
		return getResult(message, success);
	}
	
	
	@RequestMapping(value="/loadResourceWithRole")
	@ResponseBody
	public ResultMessage loadResourceWithRole(int roleId){
		try{
			List<MenuRole> menuRoleList = menuService.findMenuWithRoleId(roleId);
			return getResult("成功", true, menuRoleList,0);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("获取角色对应的授权资源列表异常", e);
		}
		return getResult("", true, null, 0);
	}

	@RequestMapping(value="/findUserRoleWithRoleId")
	@ResponseBody
	public String findUserRoleWithRoleId(HttpServletRequest request){
		try{
			int page = ServletRequestUtils.getIntParameter(request, "start", 0);
			int limit = ServletRequestUtils.getIntParameter(request, "length", 10);
			int roleId = ServletRequestUtils.getIntParameter(request, "roleId", -1);
			String query = ServletRequestUtils.getStringParameter(request, "search[value]");
			QueryBuilder queryBuilder = new QueryBuilder(UserRole.class.getName());
			queryBuilder.add(new Query("roleId",EMatchMode.EQUAL,roleId));
			
			if(StringUtils.isNotBlank(query)){
				queryBuilder.add(new Query(EAndOR.AND, "userName", EMatchMode.LIKE, query));
			}
			
			page = (page / limit) + 1;
			Pager<UserRole> pager = roleService.findUserRoleByPager(queryBuilder, limit, page);
			if (pager != null && pager.getPagerList() != null
					&& pager.getPagerList().size() > 0) {
				return getGridJsonForBootstrap(JsonMapper.toJsonString(pager.getPagerList()),
						pager.getTotalRow());
			}
		}catch(Exception e){
			logger.error("获取角色对应的授权用户列表异常", e);
		}
		return getGridJsonForBootstrap("[]", 0);
	}
	
	@RequestMapping(value="/saveResourceRole")
	@ResponseBody
	public ResultMessage saveResourceRole(HttpServletRequest request) {
		try {
			String ids = ServletRequestUtils.getStringParameter(request, "ids");
			int roleId = ServletRequestUtils.getIntParameter(request, "roleId", -1);
			
			if (StringUtils.isNotBlank(ids) && roleId != -1) {
				List<ResourceRole> list = new ArrayList<ResourceRole>();
				if (ids.contains(",")) {
					String[] idArray = ids.split(",");
					for (int i = 0; i < idArray.length; i++) {
						ResourceRole resRole = new ResourceRole(Integer.parseInt(idArray[i]), roleId);
						list.add(resRole);
					}
				} else {
					ResourceRole resRole = new ResourceRole(Integer.parseInt(ids), roleId);
					list.add(resRole);
				}
				
				return roleService.saveResoucreRole(list, roleId);
			}
		} catch (ServletRequestBindingException e) {
			logger.error("保存角色权限异常", e);
		}
		return new ResultMessage("保存角色权限失败", false);
	}
	
	@RequestMapping(value = "addRoleUser")
	@ResponseBody
	public ResultMessage addLabelsUser (HttpServletRequest request, HttpServletResponse response) {
		try {
			String ids = ServletRequestUtils.getStringParameter(request, "ids");
			int roleId = ServletRequestUtils.getIntParameter(request, "roleId");
			String message = "";
			if (StringUtils.isNotBlank(ids)) {
				List<UserRole> urList  = new ArrayList<UserRole>();
				String[] idArray = ids.split(",");
				for (String id : idArray) {
					Employees emp = employeesService.findEmployeesByWorkNo(id);
					
					boolean b = roleService.checkUserRole(emp.getEmpCode() + "");
					if (!b) {
						UserRole ur = new UserRole(emp, roleId);
						urList.add(ur);
					} else {
						message += "[" + emp.getEmpName() + "]";
					}
				}
				if (urList.size() > 0) {
					roleService.saveUserRole(urList);
				}
			}
			if (StringUtils.isNotBlank(message)) {
				message = "用户" + message + "已经授权,请勿重复授权";
				return getResult(message, true);
			}
			return getResult("添加授权用户成功", true);
		} catch (ServletRequestBindingException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return getResult("添加授权用户成功失败", false);
	}
	
	// 移除用户授权
	@RequestMapping(value = "deleteUserRole")
	@ResponseBody
	public ResultMessage deleteLabelsMenber (HttpServletRequest request, HttpServletResponse response) {
		boolean b;
		try {
			int urId = ServletRequestUtils.getIntParameter(request, "urId");
			int [] urIds = {urId};
			b = roleService.deleteUserRole(urIds);
			if (b) {
				return getResult("移除成功", b);
			}
		} catch (ServletRequestBindingException e) {
			logger.error("移除用户授权异常", e);
		}
		return getResult("移除失败", false);
	}
	
	/**
	 * 根据查询条件获取用户列表
	 * @param empName
	 * @param empCode
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="getEmployeesList")
	@ResponseBody
	public String getEmployeesList(String empNameOrCode,String phone,Integer roleId){
		List<Employees> list = employeesService.findEmployeesByCondition(empNameOrCode, phone, "binded", roleId);
		return getTableJsonString(JsonMapper.toJsonString(list),list.size());
	}
	
	/**
	 * 角色绑定选中的用户
	 * @param empId
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="bindEmployeeRole")
	@ResponseBody
	public ResultMessage bindEmployeeRole(String empIds,Integer roleId){
		if(!StringUtils.isBlank(empIds) && roleId != null){
			boolean flag = employeesService.bindUserRole(empIds, roleId);
			if(flag){
				return getResult("绑定成功", flag);
			}else{
				return getResult("绑定失败", flag);
			}
		}
		return getResult("绑定失败", false);
	}
	
	/**
	 * 获取未绑定/已绑定的用户列表
	 * @return
 	 */
	@RequestMapping(value="getBindedOrUnbindEmployeesList")
	@ResponseBody
	public String getEmployeesList(String type,Integer roleId,String empName){
		List<Employees> list = employeesService.findBindedOrUnbindEmployeesList(type, roleId,empName);
		return getTableJsonString(JsonMapper.toJsonString(list),list.size());
	}
	
	/**
	 * 解除角色用户绑定
	 * @param empId
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="unBindEmployeeRole")
	@ResponseBody
	public ResultMessage unBindEmployeeRole(String  empId,Integer roleId){
		if(!StringUtils.isBlank(empId) && roleId != null){
			boolean flag = employeesService.unbindUserRole(empId, roleId);
			if(flag){
				return getResult("解除绑定成功", flag);
			}else{
				return getResult("解除绑定失败", flag);
			}
		}
		return getResult("绑定失败", false);
	}
	
	/**
	 * 根据角色id查询菜单信息
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="getMenusInfo")
	@ResponseBody
	public JSONObject getMenusInfo(Integer roleId){
		JSONObject result = new JSONObject();
		try {
			JSONArray rowArray = new JSONArray();
			JSONObject row = new JSONObject();
			//根据roleId查询已经关联的菜单
			List<Menu> bindedAllSubList = menuService.findSubMenusByRoleId(roleId);
			List<Menu> parentList = menuService.findParentMenu(null);
			for(Menu parentObj:parentList){
				JSONObject parentObjJson = new JSONObject();
				parentObjJson.put("menuId", parentObj.getMenuId());
				parentObjJson.put("menuName", parentObj.getMenuName());
				List<Menu> subListByParent = menuService.findMenuByParentId(parentObj.getMenuId());
				JSONArray subArr = new JSONArray();
				boolean parentMenuBindStatus = true;
				for(Menu subByParent:subListByParent){
					JSONObject subByParentJson = new JSONObject();
					subByParentJson.put("menuId", subByParent.getMenuId());
					subByParentJson.put("menuName", subByParent.getMenuName());
					boolean subMenuBindStatus = false;
					for(int i=0;i<bindedAllSubList.size();i++){
						Menu bindedSub = bindedAllSubList.get(i);
						if(subByParent.getMenuId() == bindedSub.getMenuId()){
							subByParentJson.put("checked", true);
							subMenuBindStatus = true;
							continue;
						}
					}
					if(!subMenuBindStatus){
						subByParentJson.put("checked", false);
						parentMenuBindStatus = false;
					}
					subArr.add(subByParentJson);
				}
				if(parentMenuBindStatus){
					parentObjJson.put("checked", true);
				}else{
					parentObjJson.put("checked", false);
				}
				if(subListByParent.size() > 0){
					row.put("parent", parentObjJson);
					row.put("sub", subArr);
					rowArray.add(row);
				}
			}
			result.put("data", rowArray);
			result.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
		}
		return result;
	}
	
	/**
	 * 角色绑定资源信息
	 * @param bindIds
	 * @param unbindIds
	 * @param roleId
	 * @return
	 */
	@RequestMapping(value="saveRoleMenuBindInfo")
	@ResponseBody
	public ResultMessage saveRoleMenuBindInfo(String bindIds,String unbindIds,Integer roleId){
		boolean flag = employeesService.saveRoleMenuBindInfo(bindIds, unbindIds, roleId);
		if(flag){
			return getResult("绑定成功", flag);
		}else{
			return getResult("绑定失败", flag);
		}
	}
}
